# Create your views here.
from django.shortcuts import render,get_object_or_404, render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from polls.models import Poll, Choice
from django.utils import simplejson 
import re   
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
    
def autocompletion(request):
    if request.is_ajax():
        q = request.GET.get('term', '')   
        tab_polls = Poll.objects.filter(question__istartswith=q)
        results = []
        for p in tab_polls:
            tab_questions = {}
            
            tab_questions['id'] = p.id
            tab_questions['label'] = p.question
            tab_questions['value'] = p.question
            
            results.append(tab_questions)
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def search(request): 
    q = request.GET.get('term', '')  
    question = re.sub(r'_', " ", q);
    
    p = Poll.objects.filter(question__exact= question)
    message = "kiki"
    if message == None or message == "":
        message = 'Aucun message transmis'
    return HttpResponse("Message : "+message)
    """
    le_pool = {}
    le_pool['id'] = p.id
    
    results = []
    results.append(le_pool)
    data = simplejson.dumps(results)
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)"""



